const axios = require('axios');

// 配置
const BASE_URL = 'http://localhost:3000/api';
const JWT_TOKEN = 'your_jwt_token_here'; // 替换为实际的JWT token

// 设置请求头
const headers = {
  'Authorization': `Bearer ${JWT_TOKEN}`,
  'Content-Type': 'application/json'
};

// 测试随机性验证
async function testRandomnessVerification() {
  try {
    console.log('🎲 开始测试随机短剧的随机性...\n');
    
    if (JWT_TOKEN === 'your_jwt_token_here') {
      console.log('⚠️  请先设置有效的JWT token');
      console.log('   在脚本中修改 JWT_TOKEN 变量的值\n');
      return;
    }

    const testCount = 3; // 每次获取3条短剧
    const testRounds = 5; // 测试5轮
    const allResults = [];

    console.log(`📊 测试配置: 每轮获取${testCount}条短剧，共测试${testRounds}轮\n`);

    // 进行多轮测试
    for (let round = 1; round <= testRounds; round++) {
      console.log(`🔄 第${round}轮测试...`);
      
      try {
        const response = await axios.get(
          `${BASE_URL}/shorts/random?count=${testCount}`,
          { headers }
        );
        
        const shorts = response.data;
        const shortIds = shorts.map(short => short.id);
        
        console.log(`✅ 第${round}轮成功获取 ${shorts.length} 条短剧`);
        console.log(`   短剧ID: [${shortIds.join(', ')}]`);
        
        // 显示短剧标题
        shorts.forEach((short, index) => {
          console.log(`   短剧${index + 1}: ${short.title} (ID: ${short.id})`);
        });
        
        allResults.push({
          round,
          shortIds,
          titles: shorts.map(s => s.title)
        });
        
      } catch (error) {
        console.log(`❌ 第${round}轮失败:`, error.response?.data?.message || error.message);
        allResults.push({ round, shortIds: [], titles: [] });
      }
      
      console.log('');
      
      // 等待一小段时间，避免请求过于频繁
      if (round < testRounds) {
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }

    console.log('─'.repeat(50));
    console.log('📈 随机性分析结果:\n');

    // 分析随机性
    const allIds = allResults.flatMap(result => result.shortIds);
    const uniqueIds = [...new Set(allIds)];
    const totalRequests = testRounds * testCount;
    
    console.log(`📊 统计信息:`);
    console.log(`   总请求数量: ${totalRequests}`);
    console.log(`   返回的短剧总数: ${allIds.length}`);
    console.log(`   唯一短剧数量: ${uniqueIds.length}`);
    console.log(`   重复率: ${((totalRequests - uniqueIds.length) / totalRequests * 100).toFixed(2)}%`);

    // 检查每轮的重复情况
    console.log(`\n🔄 各轮结果对比:`);
    for (let i = 0; i < allResults.length; i++) {
      for (let j = i + 1; j < allResults.length; j++) {
        const round1 = allResults[i];
        const round2 = allResults[j];
        const commonIds = round1.shortIds.filter(id => round2.shortIds.includes(id));
        const similarity = (commonIds.length / testCount * 100).toFixed(2);
        
        console.log(`   第${round1.round}轮 vs 第${round2.round}轮: ${commonIds.length}个相同 (相似度: ${similarity}%)`);
        if (commonIds.length > 0) {
          console.log(`     相同ID: [${commonIds.join(', ')}]`);
        }
      }
    }

    // 检查是否有完全相同的轮次
    const duplicateRounds = [];
    for (let i = 0; i < allResults.length; i++) {
      for (let j = i + 1; j < allResults.length; j++) {
        const round1 = allResults[i];
        const round2 = allResults[j];
        if (JSON.stringify(round1.shortIds.sort()) === JSON.stringify(round2.shortIds.sort())) {
          duplicateRounds.push([round1.round, round2.round]);
        }
      }
    }

    if (duplicateRounds.length > 0) {
      console.log(`\n⚠️  发现完全相同的轮次:`);
      duplicateRounds.forEach(([round1, round2]) => {
        console.log(`   第${round1}轮和第${round2}轮结果完全相同`);
      });
    } else {
      console.log(`\n✅ 所有轮次结果都不完全相同`);
    }

    // 随机性评分
    const randomnessScore = Math.max(0, 100 - (duplicateRounds.length * 20));
    console.log(`\n🎯 随机性评分: ${randomnessScore}/100`);
    
    if (randomnessScore >= 80) {
      console.log(`🎉 随机性很好！`);
    } else if (randomnessScore >= 60) {
      console.log(`👍 随机性良好`);
    } else if (randomnessScore >= 40) {
      console.log(`😐 随机性一般`);
    } else {
      console.log(`😞 随机性较差，可能存在重复`);
    }

    console.log('\n✨ 随机性验证测试完成！');
    console.log('\n💡 测试要点:');
    console.log('   - 验证每次调用返回不同的短剧组合');
    console.log('   - 分析重复率和相似度');
    console.log('   - 评估随机算法的效果');
    console.log('   - 确保真正的随机性');

  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error.message);
  }
}

// 运行测试
testRandomnessVerification().catch(console.error); 